﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.WebPages;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using SERVICES.Services;
using WebMatrix.WebData;
using WMILK_MVC4.Helper;
using WMILK_MVC4.Models;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

namespace WMILK_MVC4.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserModels user)
        {
            if (ModelState.IsValid)
            {
                if (user.IsValid(user.UserName, user.Password))
                {
                    if (user.IsActive(user.UserName))
                    {
                        FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
                        //fixed by me KhanhHuynh
                        //Roles.AddUserToRole(user.UserName, "admin");
                        var u = SERVICES.Services.UserServices.GetUserByUserName(user.UserName);
                        if(u!=null)
                            Session["Roles"] = u.US_ROLE==1?"admin":"no";
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ViewBag.IsActiveMessage =
                            "Tài khoản của bạn chưa được kích hoạt vui lòng kiểm tra lại email của bạn";
                        ViewBag.IsActiveMessage = false;
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            }
            return View();
        }

        [HttpGet]
        public ActionResult ResendCodeRegister()
        {
            return View();
        }


        [HttpPost]
        public ActionResult ResendCodeRegister(ResendCodeUserModel resendCodeUserModel)
        {
            if (Session["Captcha"] == null || Session["Captcha"].ToString() != resendCodeUserModel.Captcha)
            {
                ModelState.AddModelError("Captcha", "Phép tính sai! Vui lòng thử lại.");
                //dispay error and generate a new captcha 
            }
            else
            {
                resendCodeUserModel.GetUserByMail();

                string body = "Chào bạn:" + resendCodeUserModel.FullName;
                body += "<br /><br />Vui lòng click vào link bên dưới để hoàn tất việc đăng ký của bạn:";

                body += "<br/><a href=" + Request.Url.GetLeftPart(UriPartial.Authority) +
                        Url.Action("ConfirmRegister", "User",
                            new { userName = resendCodeUserModel.UserName, activation = resendCodeUserModel.Activation }) +
                        ">Click vào đây để hoàn tất việc đăng ký của bạn</a>";
                body += "<br/><br/>Cám ơn!!!";
                var mail = new MailMessage("webmilk.cangle@gmail.com", resendCodeUserModel.Email)
                {
                    Subject = "WebMilk - Gửi lại xác nhận đăng ký tài khoản tại WebMilk",
                    Body = body,
                };
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    UseDefaultCredentials = false,
                    Credentials = new System.Net.NetworkCredential("webmilk.cangle@gmail.com", "webmilk.cang"),
                    EnableSsl = true,
                };
                mail.IsBodyHtml = true;
                smtp.Send(mail);

                return RedirectToAction("RegisterRequest", "User");
            }
            return View();
        }

        [HttpGet]
        public ActionResult Register()
        {
            
            return View();
        }

        public ActionResult ConfirmRegister(string userName, Guid activation)
        {
            var registerUserModels = new RegisterUserModels();

            if (registerUserModels.ConfirmRegister(userName, activation))
            {
                ViewBag.IsConfirm = true;
            }
            else
            {
                ViewBag.IsConfirm = false;
            }
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterUserModels registerUserModels)
        {
            registerUserModels.Activation = Guid.NewGuid();
            if (Session["Captcha"] == null || Session["Captcha"].ToString() != registerUserModels.Captcha)
            {
                ModelState.AddModelError("Captcha", "Phép tính sai! Vui lòng thử lại.");
                //dispay error and generate a new captcha 
            }
            else if (registerUserModels.Register())
            {

                string body = "Chào bạn:" + registerUserModels.FullName;
                body += "<br /><br />Vui lòng click vào link bên dưới để hoàn tất việc đăng ký của bạn:";

                body += "<br/><a href=" + Request.Url.GetLeftPart(UriPartial.Authority) +
                        Url.Action("ConfirmRegister", "User",
                            new {userName = registerUserModels.UserName, activation = registerUserModels.Activation}) +
                        ">Click vào đây để hoàn tất việc đăng ký của bạn</a>";
                body += "<br/><br/>Cám ơn!!!";
                var mail = new MailMessage("webmilk.cangle@gmail.com", registerUserModels.Email)
                {
                    Subject = "WebMilk - Xác nhận đăng ký tài khoản tại WebMilk",
                    Body = body,
                };
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    UseDefaultCredentials = false,
                    Credentials = new System.Net.NetworkCredential("webmilk.cangle@gmail.com", "webmilk.cang"),
                    EnableSsl = true,
                };
                mail.IsBodyHtml = true;
                smtp.Send(mail);

                return RedirectToAction("RegisterRequest", "User");
            }
            else
            {
                ViewBag.ErrorMessage = "Tên đăng nhập hay email của bạn đã tồn tại trong hệ thống! Vui lòng sử dụng tên khác.";
            }
            return View(registerUserModels);
        }

        [HttpGet]
        public ActionResult RegisterRequest()
        {
            return View();
        }
        [HttpGet]
        public ActionResult ChangePassWord()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassWord(ChangePasswordUserModel changePasswordUserModel)
        {
            if (Request.IsAuthenticated)
            {
                changePasswordUserModel.UserName = User.Identity.Name;
                if (ModelState.IsValid)
                {
                    if (!changePasswordUserModel.ChangePassword())
                    {
                        ViewBag.ChangePassworInfo = "Mật khẩu nhập vào không đúng.";
                    }
                    else
                    {
                        ViewBag.ChangePassworInfo = "Mật khẩu của bạn đã được thay đổi.";
                    }
                }
            }
            return View();
        }

        [HttpGet]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordUserModel forgotPasswordUserModel)
        {
            if (ModelState.IsValid)
            {
                if (Session["Captcha"] == null || Session["Captcha"].ToString() != forgotPasswordUserModel.Captcha)
                {
                    ModelState.AddModelError("Captcha", "Phép tính sai! Vui lòng thử lại.");
                    //dispay error and generate a new captcha 
                }
                else if (forgotPasswordUserModel.GetForgotPassword().IsEmpty())
                {
                    ViewBag.GetForgotPassword = "Email không tồn tại trong hệ thống.";
                }
                else
                {
                    string body = "<br/>Chào bạn, mật khẩu của bạn để đăng nhập tại WebMilk là:";
                    body += "<br/> Mật khẩu: " + forgotPasswordUserModel.GetForgotPassword();
                    body += "<br/><br/>Cám ơn!";
                    body += "<br/>Webmilk";

                    var mail = new MailMessage("webmilk.cangle@gmail.com", forgotPasswordUserModel.Email)
                    {
                        Subject = "[WebMilk] - Lấy lại mật khẩu tại WebMilk",
                        Body = body,
                    };

                    mail.IsBodyHtml = true;
                    var smtp = new SmtpClient
                    {
                        Host = "smtp.gmail.com",
                        Port = 587,
                        UseDefaultCredentials = false,
                        Credentials = new System.Net.NetworkCredential("webmilk.cangle@gmail.com", "webmilk.cang"),
                        EnableSsl = true,
                    };
                    
                    smtp.Send(mail);

                    ViewBag.GetForgotPassword =
                        "Mật khẩu của bạn đã được gửi qua email của bạn, vui lòng kiểm tra email của bạn.";
                }
            }
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            if (Session != null && Session["Roles"] != null)
            {
                Session["Roles"] = null;
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult CaptchaImage(string prefix, bool noisy = true)
        {
            var rand = new Random((int)DateTime.Now.Ticks);
            //generate new question 
            int a = rand.Next(10, 99);
            int b = rand.Next(0, 9);
            var captcha = string.Format("{0} + {1} = ?", a, b);

            //store answer 
            Session["Captcha" + prefix] = a + b;

            //image stream 
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(130, 30))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                //add noise 
                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 10; i++)
                    {
                        pen.Color = Color.FromArgb(
                            (rand.Next(0, 255)),
                            (rand.Next(0, 255)),
                            (rand.Next(0, 255)));

                        r = rand.Next(0, (130 / 3));
                        x = rand.Next(0, 130);
                        y = rand.Next(0, 30);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //add question 
                gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

                //render as Jpeg 
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = this.File(mem.GetBuffer(), "image/Jpeg");
            }

            return img;
        }

        public ActionResult Manage(AccountController.ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == AccountController.ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == AccountController.ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == AccountController.ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = AccountController.ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = AccountController.ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new AccountController.ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
